<?php

//文件互斥锁
Class FileLock{
    protected $file;
    protected $fileRource;
    protected $block; //是否是阻塞的锁
    function __construct($file = 'lock_file.txt',$block = false)
    {
        $this->file = app()->getRuntimePath() . $file;
        $this->block = $block;
    }

    /**
     * 获取一个文件锁
     * @return bool
     */
    public function lock()
    {
        $this->fileRource = fopen($this->file, 'w+');
        if ($this->block) {
            //阻塞的锁
            //如果一次来10个请求,那机会出现排队等待的情况,程序不会返回false
            if (flock($this->fileRource, LOCK_EX)) {
                return true;
            }
        } else {
            //非阻塞的锁
            //如果一次来10个请求,另外9个会自己返回flse
            if (flock($this->fileRource, LOCK_EX|LOCK_NB)) {
                return true;
            }
        }

        return false;
    }
    /**
     * 释放一个文件锁
     * @return bool
     */
    public function unlock()
    {
        return flock($this->fileRource, LOCK_UN);
    }
}
